package application.authorization;

import dao.inte.UserRepository;
import domain.User;
import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jasypt.util.password.PasswordEncryptor;


/**
 * Web Session for this example.
 *
 * @author Eelco Hillenius
 */
public class RolesSession extends AuthenticatedWebSession {
    @SpringBean
    private UserRepository userRepository;
    @SpringBean
    PasswordEncryptor passwordEncryptor;

    /**
     * the current user.
     */
    private Long userId = null;
    private Roles roles = new Roles();


    public RolesSession(Request request) {
        super(request);
        InjectorHolder.getInjector().inject(this);

    }

    /**
     * Gets user.
     *
     * @return user
     */
    public User getUser() {
        if (userId == null) return null;


        return userRepository.findById(userId);
    }

    @Override
    public void signOut() {
        super.signOut();
        this.userId = null;
        this.roles = new Roles();
    }

    @Override
    public boolean authenticate(String username, String password) {
        User user = userRepository.findByLogin(username);
        if (user != null && passwordEncryptor.checkPassword(password, user.getPassword())) {
            this.userId = user.getId();
            this.roles = user.getRoles();
            return true;
        }
        return false;
    }

    public Roles getRoles() {
        return roles;
    }

    public void setRoles(Roles roles) {
        this.roles = roles;
    }
}